<template>
  <div class="form-detail">
    <div v-if="isShowPdfBox || config.isLayoutFile" :id="wps_pdfId" ref="wps_pdf" :style="iframeStyle"></div>
    <div v-else class="noPdfContent" ref="wps_pdf" id="noPdfContent">
      请先上传正文
    </div>
  </div>
</template>

<script>
import service from "@/utils/request";
import { fileUpload } from "@/api/upload/file";
import { getWpsUrl, EventType } from "@/api/document/wps"
import { generateId } from "@/utils/util";
// import CreatWpsView from "@/utils/wpsOffice/creatSdk";
export default {
  name: "ZHLX-wpsPdf",
  props: {
    config: {
      type: Object,
      default: () => { },
    },
    wpsList: {
      type: Array,
      default: () => []
    },
  },
  data() {
    return {
      wpsHeight: "100%",
      instance: undefined,
      clickedPdf: "",
      isShowPdfBox: false,
      isShowMore: false,
      isShowAbstract: false,
      abstractDetailsDialog: false,
      abstractDetails: "",
      index: 0,
      outlineData: "",
      abstractData: "",
      annotationsTimer: null,
      timeClear: null,
      currentId: "",
      isShowAbstractLook: false,
      ocrTag: true,
      activeName: 0
    };
  },
  inject: {
    visibleButtons: {
      type: Function,
      default: () => {
        return null;
      },
    },
    parameter: {
      type: Object,
      default: () => {
        return null;
      },
    },
    wpsFunction: {
      type: Object,
      default: () => {
        return {};
      },
    },
    getPdfData: {
      type: Function,
      default: () => {
        return null;
      },
    },
    setting: {
      type: Function,
      default: () => {
        return null;
      },
    },
    getDocFileId: {
      type: Function,
      default: () => {
        return null;
      },
    },
    flowThis: {
      type: Object,
      default: () => { }
    }
  },
  created() {
    if (this.wpsList.length > 0) {
      this.initWpsPdfSdk(this.wpsList[0].id)
    }
  },
  computed: {
    iframeStyle() {
      return {
        height: this.wpsHeight,
        border: "medium none",
        width: "100%",
        display: "block",
      };
    },
    pdfData() {
      if (!this.getPdfData) return;
      return this.getPdfData();
    },
    settingConfig() {
      if (!this.setting) return;
      return this.setting();
    },
    docfileId() {
      if (!this.getDocFileId) return;
      return this.getDocFileId();
    },
    wps_pdfId() {
      return "wps_pdf" + generateId();
    },
    currentWpsPdfFile() {
      return this.wpsList[0]
    }
  },
  beforeDestroy() {
    window.removeEventListener("resize", () => { });
  },
  mounted() {
    this.setPdfHeight()
    this.setNoPdfHeight();
    window.addEventListener("resize", () => {
      this.setPdfHeight();
    })
  },
  watch: {
    isShowPdfBox(val) {
      if (!val) {
        this.setNoPdfHeight();
        // if (this.isShowAbstract) {
        //   this.closeAbsHandle();
        //   this.outlineData = "";
        //   this.$eventBus.$emit("actionGetAI", 1, false);
        //   this.abstractData = "";
        //   this.$eventBus.$emit("actionGetAI", 2, false);
        // }
      }
    },
    currentWpsPdfFile: {
      deep: true,
      handler(val) {
        this.initWpsPdfSdk(val.id)
      }
    }
  },
  methods: {
    creatWpsSdk() {
      // //创建 script 元素
      // const script = document.createElement('script');
      // script.src = '/wpsOffice/web-office-sdk-solution-v2.0.5.umd.js'; // 指定脚本文件的路径
      // script.id = 'WPSSdk'
      // script.async = true; // 如果需要的话，设置脚本异步加载
      // // 将 script 元素添加到 shadow root
      // document.body.appendChild(script);
    },
    setPdfHeight() {
      this.$nextTick(() => {
        // 使用closest函数查找最近的祖先元素，该元素具有指定的类名
        const parentClassName = '.el-scrollbar__view';
        var closestParent = this.$refs.wps_pdf.closest(parentClassName);
        if (closestParent === null) return;
        // 获取父元素的高度
        const wpsClientHeight = closestParent.clientHeight;
        if (this.$refs.wps_pdf.closest('.el-form-item') === null) return;
        let styleText = this.$refs.wps_pdf.closest('.el-form-item').getAttribute('style');
        this.$refs.wps_pdf.closest('.el-form-item').setAttribute('style', this.updateCssVariableValue(styleText, 'item-height', `${wpsClientHeight}px`));
      })
    },

    updateCssVariableValue(cssString, variableName, newValue) {
      // 创建一个正则表达式来匹配CSS变量及其值
      // 注意：这里假设变量名不包含特殊字符，且值的格式是标准的（如数字+单位）
      const variableRegex = new RegExp(`(--${variableName.trim()}-variable:\\s*)(\\d+(?:px|em|rem|%|vh|vw|vmin|vmax|ch|ex|rem|pt|pc|cm|mm|in|q|s|ms|Hz|kHz|dpi|dpcm|dppx|deg|grad|rad|turn|s|ms|Hz|kHz|dpi))`, 'g');
      // 使用正则表达式替换CSS变量的值
      const updatedString = cssString.replace(variableRegex, `$1${newValue}`);
      return updatedString;
    },
    handleClick(tab, event) {
      this.initWpsPdfSdk(this.wpsList[tab].id)
    },
    closeAbsHandle() {
      this.isShowAbstract = false;
      this.isShowAbstractLook = true;
    },
    getParams(url) {
      const regex = /[?&]([^=#]+)=([^&#]*)/g;
      const params = {};
      let match;
      while ((match = regex.exec(url))) {
        params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
      }
      return params;
    },
    setNoPdfHeight() {
      // 动态解析高度
      this.$nextTick(() => {
        if (!this.parameter) return;
        let parserRef = this.parameter.parser.$refs;
        for (const key in parserRef) {
          let item = parserRef[key];
          let classNameList = ["drag-around-box", "drag-ud-box"];
          if (classNameList.includes(item.className)) {
            let heightDom = item.childNodes[0];
            let officeIframe = document.getElementById("noPdfContent");
            if (!officeIframe) return;
            officeIframe.style.height = heightDom.clientHeight + "px";
          }
        }
      });
    },

    async initWpsPdfSdk(tab) {
      this.isShowPdfBox = false;
      this.setPdfHeight();
      if (document.querySelector('#WPSSdk') == null) {
        await this.creatWpsSdk()
      }
      if (this.timeClear) {
        clearInterval(this.timeClear)
        this.timeClear = null
      }
      if (this.instance) {
        await this.instance.destroy()
      }
      let id = tab.name ? tab.name : tab;
      this.currentId = id;
      let type = 'edit';
      if (this.config.disabled) {
        type = 'preview';
      }
      this.$emit("input", id);
      getWpsUrl(id, type == 'edit' ? EventType.edit : EventType.preview).then(async (res) => {
        //判断收文如果打开的地址不是pdf类型直接返回
        var path = res.data.link.split("/weboffice/office/")[1]; // 获取 /weboffice/office/ 后面的部分
        if (path && path.charAt(0) !== "f") {
          console.log("打开的不是pdf");
          return;
        }
        sessionStorage.setItem("wpsId", id);
        this.isShowPdfBox = true;
        // this.getOcResponse(id);
        this.$nextTick(async () => {
          let sdkUrl = ''
          if (res.data.link) {
            sdkUrl = res.data.link;
          }
          this.instance = await new WebOfficeSDK({
            mode: 'nomal',
            mount: this.$refs.wps_pdf,
            url: sdkUrl, // 文字自定义配置
            wordOptions: {
              isShowDocMap: false, // 是否开启目录功能，默认开启
              mobile: {
                isOpenIntoEdit: false, // （Mobile）要有编辑权限，移动端打开时是否进入编辑
              }
            },
            // 自定义的命令栏
            commandBars: [
              {
                // 命令栏的 ID
                cmbId: "FloatQuickHelp", // 右下角帮助（金小獴）
                // 命令栏的属性设置
                attributes: {
                  // 隐藏命令栏
                  visible: false, // 隐藏组件
                  // 禁用命令栏（组件显示但不响应点击事件）
                  enable: false, // 禁用组件（组件显示但不响应点击事件）
                },
              },
            ],
          })
          // if (this.config && this.config.disabled !== undefined) {
          //   _config.commonOptions.isShowTopArea = !this.config.disabled;
          // }
          // if (this.instance) {
          //   this.instance.ApiEvent.AddApiEventListener(
          //     "fileOpen",
          //     (data) => {
          //       if (data.fileInfo.officeType !== "f") {
          //         this.instance.destroy();
          //       }
          //       console.log("fileOpen: ", data);
          //       this.setPdfHeight();
          //       this.initFun();
          //     }
          //   );
          // }
          window[this.wps_pdfId] = this.instance;
          try {
            await this.instance.advancedApiReady();
            let _this = this
            this.timeClear = setInterval(function () {
              if(!_this.$refs.wps_pdf){
                clearInterval(_this.timeClear);
                return;
              };
              _this.setPdfHeight();
              let officeIframe = _this.$refs.wps_pdf.getElementsByClassName("web-office-iframe")[0];
              officeIframe && (officeIframe.style.width = 99 + "%") && (officeIframe.style.height = (_this.$refs.wps_pdf.clientHeight - 10) + 'px');
            }, 500);
            this.initFun();
            this.$emit("setWpsId", this.wps_pdfId)
            const app = this.instance.Application;
            // app.Sub.Scroll = (data) => {
            //   this.isShowAbstract = true;
            // };
            // 开启限制编辑
            if (this.config.disabled) {
              const ReadOnly = await app.ActivePDF.ReadOnly;
            }
            // 定义右键菜单
            if (this.config.morePermissions.wpsControlsMenu && this.config.morePermissions.wpsControlsMenu.length) {
              const controls = await app.CommandBars('TextMenu').Controls;
              // 新增按钮型定制元素 1 是可控按钮 10 是可控的下拉框
              this.config.morePermissions.wpsControlsMenu.forEach(async item => {
                const controlButton = await controls.Add(1);
                controlButton.Caption = item.name;
                controlButton.Picture = item.icon;
                controlButton.OnAction = () => item.callBack()
              });
            }
            // 将当前文档的编辑状态切换成修订模式
            app.ActivePDF.TrackRevisions = true;
            // 对文档窗口大小进行调整后，是否缩放视图以适应文档窗口的尺寸 
            // -1：文档窗口大小进行调整后使页面以最佳尺寸适应活动窗口
            // 0：对文档窗口大小进行调整后不为适应文档窗口尺寸而缩放视图
            app.ActivePDF.ZoomToFit = 0;
          } catch (error) {
            console.log(error);
          }
        });

      });
    },
    initFun() {
      this.wpsFunction.fileUpload = this.fileUpload;
      this.wpsFunction.wpsDocumentTrackRevisions =
        this.wpsDocumentTrackRevisions;
      this.wpsFunction.wpsSaveDoc = this.wpsSaveDoc;
      this.wpsFunction.example = this.examplePdf;
      this.wpsFunction.getPageCount = this.getPageCount;
      window[this.wps_pdfId].functionObj = this.wpsFunction;
      this.examplePdf()
      if (this.instance && this.wpsFunction) {
        this.instance.functionObj = this.wpsFunction;
      }
    },
    async getPageCount() {
      await this.instance.advancedApiReady();
      const app = this.instance.Application;
      // 获取总页数
      const totalPages = await app.ActivePDF.PagesCount;
      console.log(totalPages);
      return totalPages;
    },
    //@file=base.pdf
    async examplePdf() {
      await this.instance.advancedApiReady()
      // console.log(1111111);
      const app = this.instance.Application

      // 获取窗口缩放比例
      const result = await app.ActivePDF.Zoom
      console.log(result)

      // 设置窗口缩放比例
      app.ActivePDF.Zoom = 100
    },

    async fileUpload(param) {
      try {
        let file = param.file;
        let formData = new FormData();
        formData.append("file", file);
        fileUpload("oapdf", formData).then(async (res) => {
          let id = res.data.id;
          sessionStorage.setItem("wpsId", id);
          this.$emit("input", id);
          this.$eventBus.$emit("upLoadFileSuccessEventBus", res.data, "pdf");
          this.initWpsPdfSdk(id);
        });
      } catch (e) { }
    },
    async getOcResponse(id, isUpload = false) {
      this.$eventBus.$emit("actionGetAI", 1, true);
      this.$eventBus.$emit("actionGetAI", 2, true);
      this.ocrTag = false;
      let hasBtnList = this.visibleButtons();
      let flag = hasBtnList
        .map((item) => item.key)
        .some((el) => el === "abstract" || el === "outline");
      // let ocrFlag = true; //默认给true接口目前有问题
      // await service({
      //   url: `/api/system/organizeCapability/ `,//空格是值不要删
      //   method: "get",
      // }).then((res) => {
      //   if (
      //     res.data.authCapabilityComponentList.find(
      //       (item) => item.capName === "OCR"
      //     )
      //   ) {
      //     ocrFlag = true;
      //   }
      // });
      if (!flag && !isUpload) return;
      service({
        url: `api/ocr/file/ocrUploader/${id}`,
        method: "post",
      })
        .then((res) => {
          if (res.code == 200) {
            if (flag) {
              let data = JSON.parse(res.msg).data.docText;
              this.getChatRecordCreateData(data, 1);
              this.getChatRecordCreateData(data, 2);
              this.ocrTag = true;
            }
            if (isUpload) {
              const parseData = JSON.parse(res.msg).data;
              this.$eventBus.$emit("initFileWithOcr", parseData);
            }
          }
        })
        .catch((err) => {
          this.ocrTag = false;
          this.$eventBus.$emit("actionGetAI", 1, false);
          this.$eventBus.$emit("actionGetAI", 2, false);
        });
    },
    getChatRecordCreateData(textData, parameter) {
      let text = parameter == 1 ? "大纲" : "摘要";
      // const params = {
      //   paramList: [
      //     {
      //       // field: "1",
      //       field: "chatAppId",
      //       fieldName: "应用标识",
      //       dataType: "int",
      //       required: 0,
      //       defaultValue: parameter == 1 ? "4" : "5", // this.active,
      //     },
      //     {
      //       field: "query",
      //       fieldName: "查询内容",
      //       dataType: "varchar",
      //       required: 0,
      //       defaultValue: textData.replace(/\n/g, "\\n") || "",
      //     },
      //   ],
      //   tenantId: "",
      //   origin: "preview",
      // };
      const params = {
        chatAppId: parameter == 1 ? "4" : "5",
        query: textData,
      };
      postChatRecordCreateV1(params)
        .then((res) => {
          if (res.code == 200) {
            this.getChatRecordStatusData(res.data.recordId, parameter);
          }
        })
        .catch((err) => {
          this.$message({
            message: "AI服务异常",
            type: "error",
          });
          this.$eventBus.$emit("actionGetAI", parameter, false);
        });
    },
    // 获取对话排队状态
    async getChatRecordStatusData(recordId, parameter) {
      try {
        ++this.index;
        const params = {
          paramList: [
            {
              field: "recordId",
              fieldName: "对话id",
              dataType: "int",
              required: 0,
              defaultValue: recordId,
            },
          ],
          tenantId: "",
          origin: "preview",
        };
        // const resData = await getChatRecordStatus(params);
        getChatRecordStatus(params)
          .then((resData) => {
            if (resData.code === 200) {
              if (resData.data.num > 0) {
                this.getChatRecordStatusData(recordId, parameter);
              } else {
                this.getChatRecordResultData(recordId, parameter);
              }
            } else {
              this.$message.error(resData.msg);
              this.loading = false;
            }
          })
          .catch((err) => {
            this.$message({
              message: "AI服务异常",
              type: "error",
            });
            this.$eventBus.$emit("actionGetAI", parameter, false);
          });
      } catch (error) {
        if (this.index < 5) {
          this.getChatRecordStatusData(recordId);
        }
      }
    },
    // 获取对话结果
    getChatRecordResultData(recordId, parameter) {
      this.newText = "";
      const params = {
        paramList: [
          {
            field: "recordId",
            fieldName: "记录id",
            dataType: "int",
            required: 0,
            defaultValue: recordId,
          },
        ],
        tenantId: "",
        origin: "preview",
      };
      let _that = this;
      // // ${recordId}
      // fetchEventSource(`${APIURl}/api/ai/chat/record/result/${recordId}`, {
      //   onopen(e) {},
      //   onmessage(e) {
      //     let text = {};
      //     if (e.data) {
      //       text = JSON.parse(e.data);
      //       if (text.recordId && text.history) {

      //       }
      //     }
      //   },
      //   onclose(e) {
      //     if (parameter == 2) {
      //       _that.getOcResponse(_that.currentId, 1);
      //     }
      //   },
      //   onerror(err) {
      //     _that.loading = false;
      //     // _that.$message({
      //     //   message: "AI服务异常",
      //     //   type: "error",
      //     // });
      //     _that.$eventBus.$emit("actionGetAI", parameter, false);
      //     throw err;
      //   },
      // });

      getChatRecordResult(params)
        .then((res) => {
          if (res.code === 400) {
            this.getChatRecordResultData(recordId);
          } else if (res.code === 200) {
            if (res.data.answer && this.ocrTag) {
              if (parameter == 1) {
                _that.outlineData = res.data.answer;
                _that.$eventBus.$emit(
                  "pdfPluginAiHttpClose",
                  _that.outlineData,
                  "outline"
                );
              } else {
                _that.abstractData = res.data.answer;
                _that.isShowAbstractLook = false;
                _that.$eventBus.$emit(
                  "pdfPluginAiHttpClose",
                  _that.abstractData,
                  "abstract"
                );
              }
            }
          }
        })
        .catch((err) => {
          console.log(err);
          _that.$eventBus.$emit("actionGetAI", parameter, false);
        });
    },
    hasMoreClickHandle() {
      this.$eventBus.$emit("pdfPluginAiabstractShow", this.abstractData);
    },
    closeOutlineDetail(bool) {
      if (bool) {
        this.isShowAbstract = bool;
      }
      this.abstractDetailsDialog = false;
    },
    openOutlineDetail() {
      this.abstractDetailsDialog = true;
    },
    async setAnnotations(app) {
      const totalPages = (await app.ActivePDF.PagesCount) || 0;
      let totalContent = [];
      let counter = 0;
      if (!totalPages || totalPages == 0) return;
      for (let i = 1; i <= totalPages; i++) {
        let pageData = await app.ActivePDF.PageTextData(i);
        let result = pageData[0].content;
        let content = result.match(/中央/g);
        if (!!content) {
          totalContent = [...totalContent, ...content];
        }
      }
      const executeNum = totalContent.length;
      if (!executeNum || executeNum <= 0) return;
      this.annotationsTimer = setInterval(async () => {
        await app.ActivePDF.Find({ Value: "中央" });
        // await app.ActivePDF.FindNext();
        // app.ActivePDF.ScrollTo(0, 0);
        await app.ActivePDF.AnnoAPI.SetSelectionAnno({
          type: app.Enum.AnnoType.Highlight,
          color: "rgba(240,206,112,1)",
        });
        counter++;
        if (counter >= executeNum) {
          clearInterval(this.annotationsTimer);
          this.annotationsTimer = null;
          // app.ActivePDF.DiscardFind();
          // await app.ActivePDF.ScrollTo(0, 0);
        }
      }, 1000);
      // for (let i = 0; i < count-1; i++) {
      // await app.ActivePDF.FindNext();
      // await app.ActivePDF.AnnoAPI.ClearAnnoSelection();
      // await app.ActivePDF.AnnoAPI.SetSelectionAnno({type: app.Enum.AnnoType.Highlight, color: 'rgba(24,144,255,1)'});
      // console.log('nextte',nextte);
      // }
    },
    // 设置修订模式开关
    async wpsDocumentTrackRevisions(isEdit = true) {
      // await this.instance.advancedApiReady();
      // const app = this.instance.Application;
      // app.ActivePDF.TrackRevisions = isEdit;
    },
    // 保存当前文档内容
    async wpsSaveDoc() {
      await this.instance.advancedApiReady();
      const app = this.instance.Application;
      // 保存文件的改动
      const saveResult = await app.ActivePDF.Save();
    },
  },
};
</script>

<style lang="scss" scoped>
.noPdfContent {
  width: 100%;
  height: 100%;
  text-align: center;
  font-size: 20px;
  font-weight: 600;
  display: grid;
  place-items: center;
  color: red;
  position: relative;
}

.form-detail {
  // display: flex;
  // align-items: center;
  background: #eeeeef;
  padding-right: 0;
  height: 100%;
  overflow: hidden;
  width: 100%;
}

::v-deep .el-tabs__content {
  display: none;
}

.office-container {
  width: 100%;
  background: #ffffff;

  .el-scrollbar__view {
    height: 100%;

    .form-wps {
      width: 100%;
      height: 100%;
    }
  }
}

.abstract {
  width: calc(100%);
  position: absolute;
  top: 0;
  background-color: #dae7ff !important;
  z-index: 99;
  text-align: center !important;
  margin-top: 40px;

  .abstract-title {
    padding-right: 45px;
    width: 90%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin: auto;
    color: #000000 !important;
    font-family: 微软雅黑 !important;
    font-weight: regular;
    font-size: 14px !important;
    height: 46px;
    line-height: 46px;
    letter-spacing: 0px;
    text-align: left !important;
  }

  .arrow-close {
    position: absolute;
    right: 12px;
    top: 17px;
    width: 12px;
    cursor: pointer;
  }

  .arrow-down {
    color: #004ea2 !important;
    text-align: center !important;
    cursor: pointer;
    font-size: 12px;
    float: right;
    position: absolute;
    right: 48px;
    top: 7px;

    .el-icon-arrow-down {
      margin-right: 5px;
      font-size: 16px !important;
    }
  }
}
</style>
